package com.aier.user.service.impl;



import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javassist.tools.reflect.Sample;

import javax.annotation.Resource;

import net.eicp.ghostboy.futil.MD5Util;
import net.eicp.ghostboy.futil.RandomUtil;

import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import sun.org.mozilla.javascript.internal.ObjArray;

import com.aier.classes.entity.ClassStudent;
import com.aier.classes.entity.mapper.ClassStudentRowMapper;
import com.aier.common.common.Constant;
import com.aier.common.common.PinyinUtil;
import com.aier.common.dao.ICommonDAO;
import com.aier.common.service.ISysPhoneMessageService;
import com.aier.user.entity.User;
import com.aier.user.entity.UserPhotoImg;
import com.aier.user.entity.UserPhotoType;
import com.aier.user.entity.mapper.UserPhotoImgRowMapper;
import com.aier.user.entity.mapper.UserPhotoTypeRowMapper;
import com.aier.user.entity.mapper.UserRowMapper;
import com.aier.user.service.IUserService;

@Component("userService")
public class UserServiceImpl_J implements IUserService{
    
    @Resource(name = "sysPhoneMessageService")
    private ISysPhoneMessageService sysPhoneMessageService;    
    
    @Resource(name = "commonDao")
    private ICommonDAO commonDao;

    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }

    
    
    @Override
    public String insertPhoneMessage(String phone) {
        commonDao.update("delete from sys_phone_key where phone=? ",new Object[] { phone});
        String key = RandomUtil.genRandomNum(Constant.num_4);
        commonDao.update("insert into sys_phone_key(phone,message) values(?,?) ",
                new Object[] {phone,key});
        String phoneMessage = "您本次获取的激活码是:" + key + ",30分钟内有效";
        //sysPhoneMessageService.insertSendPhoneMessage(phone, phoneMessage);
        sysPhoneMessageService.insertSchoolPhoneMessageMobile(phone, phoneMessage,null,null,0,null);
        return key;
    }

    @Override
    public int checkPhoneMessage(String phone, String message) {
        int key_num = commonDao.countByQuali("from sys_phone_key where phone=? and message=?", new Object[] { phone,message});
        return key_num;
    }

    @Override
    public User searchUserByCondition(String account) {
        return (User) commonDao.listByObject(
                "select * from user where account=?", new Object[] { account },
                new UserRowMapper());
    }
    
    @Override
    public User searchUserByNickname(String nickname) {
        return (User) commonDao.listByObject(
                "select * from user where nickname=? and isbaby = 0", new Object[] { nickname },
                new UserRowMapper());
    }
    
    @Override
    public User getUserByUid(Long uid) {
        return (User) commonDao.listByObject(
                "select * from user where uid=?", new Object[] { uid },
                new UserRowMapper());
    }

    @Override
    public int countUserByNickName(String nickName,Long uid) {
        String sql = "from user where nickname=? ";
        if(uid!=null){
            sql = sql + " and uid!=" + uid;
        }
        return commonDao.countByQuali(sql, new Object[] { nickName});
    }
    
    @Override
    public User searchUserByCondition(String account,String pwd) {
        return (User) commonDao.listByObject(
                "select * from user where account=? and pwd=?", new Object[] { account,pwd },
                new UserRowMapper());
    }
    
    @Override
    public int insertUserNormal(User user) {
        KeyHolder kh = commonDao.insert(
                UserRowMapper.getPreparedStatementCreator(user),
                new GeneratedKeyHolder());
        if(kh!=null){
            return kh.getKey().intValue();
        }else{
            return 0;
        }
    }

    @Override
    public User insertUserBabyByCondition(Long uid, String baby_name,String relation){
        User baby_user = null;
        baby_user = (User) commonDao.listByObject(
                "select * from user where nickname=? and uid in (select baby_uid from parent_baby where parent_uid=?)", 
                new Object[] { baby_name,uid},new UserRowMapper());
        if(baby_user==null){
            //添加新的宝宝
            String account = PinyinUtil.HanyuToPinyin(baby_name)+RandomUtil.genRandomNum(Constant.num_4);
            baby_user = new User(account,MD5Util.getMD5("888888"),baby_name,null);
            baby_user.setIsbaby((short) 1);
            KeyHolder kh = commonDao.insert(
                    UserRowMapper.getPreparedStatementCreator(baby_user),new GeneratedKeyHolder());
            baby_user.setUid(kh.getKey().longValue());
            commonDao.update("insert into parent_baby(parent_uid,baby_uid,relation) values (?,?,?)", 
                    new Object[] { uid,kh.getKey().longValue(),relation });
        }
        return baby_user;
    }
    
    @Override
    public Long insertUserBabyByConditionNew(Long uid, String baby_name,String relation,Long cid){
        User baby_user = null;
        @SuppressWarnings("unchecked")
        List<ClassStudent> csList = (List<ClassStudent>) commonDao.list("select * from class_student where cid = ? and sname=? ", 
                new Object[] { cid,baby_name },new ClassStudentRowMapper());
        Timestamp ctime = new Timestamp(new Date().getTime());
        Long csid = null;
        //班级学生不存在
        if (null == csList || csList.size() == 0) {
            baby_user = (User) commonDao.listByObject(
                    "select * from user where nickname=? and uid in (select baby_uid from parent_baby where parent_uid=?)", 
                    new Object[] { baby_name,uid},new UserRowMapper());
            if(baby_user==null){
                //添加新的宝宝
                String account = PinyinUtil.HanyuToPinyin(baby_name)+RandomUtil.genRandomNum(Constant.num_4);
                baby_user = new User(account,MD5Util.getMD5("888888"),baby_name,null);
                baby_user.setIsbaby((short) 1);
                KeyHolder kh = commonDao.insert(
                        UserRowMapper.getPreparedStatementCreator(baby_user),new GeneratedKeyHolder());
                baby_user.setUid(kh.getKey().longValue());
                commonDao.update("insert into parent_baby(parent_uid,baby_uid,relation) values (?,?,?)", 
                        new Object[] { uid,kh.getKey().longValue(),relation });
            }
            ClassStudent classStudent = new ClassStudent(null,
                  baby_user.getUid(), baby_name, cid, ctime);
            KeyHolder kh = commonDao.insert(ClassStudentRowMapper
                  .getPreparedStatementCreator(classStudent),
                  new GeneratedKeyHolder());// 创建班级学生
            csid = kh.getKey().longValue();
                    
        } else {
            csid = csList.get(0).getCsid();
            // 班级学生存在，根据学生uid和家长uid判断是否存在关系
            String pbid = (String)commonDao.listByObject("select pbid from parent_baby where parent_uid = ? and baby_uid = ?", 
                    new Object[]{uid,csList.get(0).getUid()},
                    new RowMapper<String>() {
                    @Override
                    public String mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getString("pbid");
                    }
                }
            );
            // 不存在
            if (null == pbid || "".equals(pbid)) {
                commonDao.update("insert into parent_baby(parent_uid,baby_uid,relation) values (?,?,?)", 
                        new Object[] { uid,csList.get(0).getUid(),relation });
            } else {
                commonDao.update("update parent_baby set relation = ? where pbid = ?", 
                        new Object[] { relation,Long.valueOf(pbid) });
            }
            
        }
        return csid;
    }
    
    @Override
    public int updateUserPwd(String account, String pwd) {
        if (commonDao.update("update user set pwd=? where account=?",
                new Object[] { pwd, account }) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int updateUserHeadImg(Long uid, String img) {
        if (commonDao.update("update user set headimg=? where uid=?",
                new Object[] { img, uid }) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int updateUserInfo(User user) {
        if (commonDao.update("update user set nickname=?,realname=?,email=?,city_id=?,address=?,birthday=?,sex=?," +
                "desinfo=?,constellation=?,interest=? ,  where uid=?",
                new Object[] { user.getNickname(),user.getRealname(),user.getEmail(),user.getCity_id(),user.getAddress()
                ,user.getBirthday(),user.getSex(),user.getDesinfo(),user.getConstellation(),user.getInterest(),user.getUid()}) > 0) {
            return 1;
        } else {
            return 0;
        }
    }
    
    @Override
    public int updateUserInfoNew(String account,String phone,String nickname) {
        if (commonDao.update("update user set nickname=?,phone=? where account=?",
                new Object[] { nickname,phone,account}) > 0) {
            return 1;
        } else {
            return 0;
        }
    }
    
    @Override
    public int updateUserInfoNew(Long uid,String email,String phone,String realname) {
    	int suss=commonDao.update("update user set email=? , nickname = ? , phone=?  where uid=? ", new Object[] { email,realname,phone,uid});
        if ( suss> 0) {
            return 1;
        } else {
            return 0;
        }
    }
    
    
    @Override
    public int updateUserCoverimg(String coverimg,Long uid) {
        if (commonDao.update("update user set coverimg=? where uid=?",
                new Object[] { coverimg,uid}) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

//=====================================================================================    
    
    @Override
    public Map<String, Object> searchUserPhotoTypeList(int page, int pagesize,
            Long uid) {
        String sql = " from user_photo_type where uid=?";
        String sql_first = sql;
        return commonDao.queryPage(
            "select * " + sql, "select count(*) " + sql_first, page,
            pagesize, new Object[] { uid }, new Object[] { uid },
            new UserPhotoTypeRowMapper());   
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<UserPhotoType> searchUserPhotoTypeList(Long uid){
        return (List<UserPhotoType>) commonDao.list("select upt.*,count(upi.upiid) as num_img  from user_photo_type upt " +
                "LEFT JOIN user_photo_img upi on upt.uptid=upi.uptid  where uid=? GROUP BY uptid",
                new Object[] { uid },new UserPhotoTypeRowMapper(UserPhotoTypeRowMapper.AND_NUM));
    }
    
    @Override
    public int insertUserPhotoType(UserPhotoType upt) {
        KeyHolder kh = commonDao.insert(
                UserPhotoTypeRowMapper.getPreparedStatementCreator(upt),
                new GeneratedKeyHolder());
        if(kh!=null){
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public UserPhotoType searchUserPhotoType(Long uptid){
        return (UserPhotoType) commonDao.listByObject("select * from user_photo_type where uptid=?", 
                new Object[] {uptid}, new UserPhotoTypeRowMapper());
    }
    

    @Override
    public UserPhotoImg searchUserPhotoImg(Long upiid) {
        return (UserPhotoImg) commonDao.listByObject("select * from user_photo_img where upiid=?", 
                new Object[] {upiid}, new UserPhotoImgRowMapper());
    }
    
    @Override
    public int updateUserPhotoType(UserPhotoType upt) {
        if (commonDao.update("update user_photo_type set pname=?,state=? where uptid=?",
                new Object[] { upt.getPname(),upt.getState(),upt.getUptid()}) > 0) {
            return 1;
        } else {
            return 0;
        }
    }
    
    @Override
    public int updateUserPhotoTypeCover(String img,Long uptid) {
        if (commonDao.update("update user_photo_type set img=? where uptid=?",
                new Object[] { img,uptid}) > 0) {
            return 1;
        } else {
            return 0;
        }
    }




    @Override
    public int deleteUserPhotoType(Long uptid) {
        if (commonDao.update("delete from user_photo_type where uptid=?",
                new Object[] {uptid }) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

//=====================================================================================    
    
    @Override
    public Map<String, Object> searchUserPhotoImgList(int page, int pagesize,
            Long uptid) {
        String sql = " from user_photo_img where uptid=? order by upiid desc";
        String sql_first = sql;
        return commonDao.queryPage(
            "select * " + sql, "select count(*) " + sql_first, page,
            pagesize, new Object[] { uptid }, new Object[] { uptid },
            new UserPhotoImgRowMapper());   
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<UserPhotoImg> searchUserPhotoImgList(Long uptid){
        return (List<UserPhotoImg>) commonDao.list("select *  from user_photo_img where uptid=? order by upiid desc",
                new Object[] { uptid },new UserPhotoImgRowMapper());
    }
    
    @Override
    public long insertUserPhotoImg(UserPhotoImg upi) {
        KeyHolder kh = commonDao.insert(
                UserPhotoImgRowMapper.getPreparedStatementCreator(upi),
                new GeneratedKeyHolder());
        if(kh!=null){
            return kh.getKey().longValue();
        }else{
            return (long)0;
        }
    }

    @Override
    public int updateUserPhotoImg(UserPhotoImg upi) {
        if (commonDao.update("update user_photo_img set img=?,desinfo=? where upiid=?",
                new Object[] { upi.getImg(),upi.getDesinfo(),upi.getUpiid()}) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int deleteUserPhotoImg(Long upiid) {
        if (commonDao.update("delete from user_photo_img where upiid=?",
                new Object[] {upiid }) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int updateUserPhotoImg_face(Long upiid) {
        int i = 0;
        UserPhotoImg upi = (UserPhotoImg) commonDao.listByObject("select * from user_photo_img where upiid=?", 
                new Object[]{upiid}, new UserPhotoImgRowMapper());
        if(upi!=null){
            if (commonDao.update("update user_photo_type set img=? where uptid=?",
                    new Object[] {upi.getImg(),upi.getUptid() }) > 0) {
                i = 1;
            } 
        }
        return i;
    }

//=====================================================================================    
    
    @SuppressWarnings("unchecked")
    @Override
    public List<User> searchUserBabyList(Long uid){
        return (List<User>) commonDao.list(
                "select u.*,(select cname from classes where cid=(select cid from class_student where uid=u.uid)) as baby_className," +
                " pb.relation from user u RIGHT JOIN parent_baby pb on u.uid=pb.baby_uid where pb.parent_uid=?",
                new Object[] {uid}, new UserRowMapper(UserRowMapper.BABY_CLASSNAME));
    }
    
    @Override
    public int deleteParentBaby(Long parent_uid, Long baby_uid){
        commonDao.update("delete from class_parent where uid=? and csid=(select csid from class_student where uid=?)", 
                new Object[] {parent_uid,baby_uid});
        commonDao.update("delete from parent_baby where parent_uid=? and baby_uid=?", new Object[] {parent_uid,baby_uid});
        return 1;
    }

    @Override
    public int updatePhoneImeiByUid(String phone_imei, Long uid){
    	commonDao.update("update user set phone_imei=? where uid=? ", new Object[] {phone_imei,uid});
    	return 1;
    }
    
    
    
    
    
    public void setSysPhoneMessageService(
            ISysPhoneMessageService sysPhoneMessageService) {
        this.sysPhoneMessageService = sysPhoneMessageService;
    }

	@Override
	public int deleteParentBabyApp(Long parent_uid) {
		 List<User> list =searchBabyByList(parent_uid);
		 if(list.size()==0)
			 return 0;
		 for(User u :list){
			 commonDao.update("delete from user where uid=? and isbaby =1 ", new Object[] {u.getUid()});
		 }
		 int i=commonDao.update("delete from user_babylist where parent_uid=? ", new Object[] {parent_uid});
		return i;
	}
	
	@Override
	public int insertParentBabyApp(Long parent_uid,Long baby_uid) {
		int sus =commonDao.update("insert into user_babylist (parent_uid,baby_id) values(?,?) ",new Object[] {parent_uid,baby_uid});
		return sus;
	}  
	
	@Override
	public int updateBabyinfo(Long parent_uid,User user){
		User u=searchBabyByUserid(user.getUid());
		if(u==null){
			User us= new User();
			us.setNickname(user.getNickname());
			us.setAccount(user.getAccount());
			us.setPwd("abc");
			us.setSex(user.getSex());
			us.setDesinfo(user.getDesinfo());
			us.setIsbaby((short)1);
			us.setBirthday(user.getBirthday());
			//插入信息
			insertUserNormal(us);
			
			User newbaby=searchUserByCondition(us.getAccount());
			
			insertParentBabyApp( parent_uid, newbaby.getUid());
			
		}else{
			updateUserapp(user);
		}
		return 1;
	}
	
    @Override
    public int updateUserapp(User user) {
    	try {
	    	 if (commonDao.update("update user set nickname=? , birthday=? , sex=? ," +
	                 " desinfo=? , interest=?  ,address=?  where uid=? ",
	                 new Object[] { user.getNickname(),user.getBirthday(),user.getSex(),user.getDesinfo(),user.getInterest(),user.getAddress(),user.getUid()}) > 0) {
	    		 return 1;
	         } else {
	             return 0;
	         }
    	} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
    }
    
	@Override
	public User searchBabyByUserid(Long uid){
		User u = (User)commonDao.listByObject("select * from user where uid = ? ",new Object []{ uid }, new UserRowMapper());
		return u;
	}
	
	@Override
	public List<User> searchBabyByList(Long uid){
		List<User> list = (List)commonDao.list("select u.*   from  user as u  , user_babylist as ubs where u.uid in "
				+ "(  select  ub.baby_id   from user_babylist as ub where  ub.parent_uid= ? )  and  u.uid =ubs.baby_id ",new Object []{uid },new UserRowMapper());
		return list;
	}



	@Override
	public int updateOrInsertAppUid(String appUid, Long uid) {
		User u = (User)commonDao.listByObject("select * from user where uid = ? and appUid=? ",new Object []{ uid,appUid }, new UserRowMapper());
		if(u==null){
			return commonDao.update("update user set appUid=? where uid=? ", new Object[] {appUid,uid});
		}
    	return 1;
	}



	@Override
	public User getAppUid(Long Uid) {
		return (User)commonDao.listByObject("select nickname,uid,appUid , headimg  from user where uid = ?",new Object []{Uid }, new UserRowMapper());
	
	}

	@Override
	public int insertUserOnline(Long uid) {
		int online =commonDao.countByQuali("select  COUNT(*)  from user_online where  uid = ?", new Object []{uid});
		
		if(online==0)
			commonDao.update("insert into user_online (uid , online) values (?,?)  ",  new Object[]{uid ,1});
		else
			commonDao.update("update  user_online set online =1 where  uid = ?  ",  new Object[]{uid});
		return 1;
	}
 

	@Override
	public boolean serachUserOnline(Long uid) {
		Integer online=commonDao.countByQuali("select  online from user_online where  uid = ?", new Object []{uid});
		
		if(online==0 | online ==null)
		return false;
		else if(online==1)
		return true;
		
		return false;
	}

	@Override
	public int updateUserOnline(Long uid) {
			commonDao.update("update  user_online set online =0 where  uid = ?  ",  new Object[]{uid});
		return 0;
	}
}
